﻿using D.B.Data.API.Applications.Command.RoleMenusCommand;
using D.B.Data.Domain;
using D.B.Data.Domain.DTO.Output;
using D.B.Data.ErrorCode;
using D.B.Data.Infrastructuse;
using MediatR;

namespace D.B.Data.API.Applications.CommandHandler.RoleMenusCommandHandler
{
    public class MenusCommandHandler : IRequestHandler<MenusCommand, APIResult<List<MenuTreeDTO>>>
    {
        private readonly IBaseRepository<MenusModel> baseRepository;

        public MenusCommandHandler(IBaseRepository<MenusModel> baseRepository)
        {
            this.baseRepository = baseRepository;
        }

        public Task<APIResult<List<MenuTreeDTO>>> Handle(MenusCommand request, CancellationToken cancellationToken)
        {
            var res = baseRepository.GetAll().Where(s=>!s.IsDel);

            var data = Find(request.Pid, res.ToList());

                APIResult<List<MenuTreeDTO>> aPIResult = new APIResult<List<MenuTreeDTO>>
                {
                     Code=EnumCode.Ok,
                     Data=data,
                     Msg="树形显示成功"
                };

            return Task.FromResult(aPIResult);  
        }



        public List<MenuTreeDTO> Find(long id,List<MenusModel>  ids)
        {
            var res= ids.Where(s=>s.Pid == id).ToList();

            List<MenuTreeDTO> menus= new List<MenuTreeDTO>();

            foreach(var item in res)
            {
                menus.Add(new MenuTreeDTO
                {
                    id= item.Id,
                     label=item.MenuName,
                     children= Find(item.Id,ids)
                });
            }

            return menus;
        }
    }
}
